<?php

namespace App\Services;

use App\Models\Article;
use App\Models\ArticleRelateCircle;
use App\Models\Comment;
use App\Models\Share;

class ArticleWeightService
{

    public static function handle($article_id)
    {
        $weight = 0;
        $article = Article::find($article_id);
        if (!$article)
            return;

        $star_num = $article->star_num;
        if ($star_num)
            $weight += $star_num;

        $share_num = Share::where('entity_id', $article->id)->where('entity_type', Share::TYPE_ARTICLE)->where('user_id', '!=', $article->user_id)->count();
        if ($share_num)
            $weight += $share_num * 13;

        $comment_length_1 = Comment::where('entity_id', $article->id)->where('comment_string_length', '>=', 15)->count();
        if ($comment_length_1)
            $weight += $comment_length_1 * 13;

        $comment_length_2 = Comment::where('entity_id', $article->id)->where('comment_string_length', '<', 15)->count();
        if ($comment_length_2)
            $weight += $comment_length_2 * 6;

        $hour = floor((time() - strtotime($article->created_at)) % 86400 / 3600);
        if ($hour < 12) {
            $weight += 3;
        } else if ($hour >= 12 && $hour < 24) {
            $weight += 2;
        } else if ($hour >= 24 && $hour < 48) {
            $weight += 1;
        }

        $article->weight = $weight;
        $article->save();

        ArticleRelateCircle::where('article_id', $article_id)->update([
            'article_weight' => $weight
        ]);
    }

}
